<template>
	<view>
		<!-- 搜索控件 -->
		<view class="search-box">
			<uni-search-bar focus v-model="searchText" @input="inputChange" placeholder=" 请输入搜索内容" radius='30'
				cancelButton="none" @clear="searchClear" />
		</view>
		<!--  搜索结果列表 -->
		<view class="searchResult" v-if="searchText.length > 0" :style="{ paddingTop: 60 + 'px'}">
			<view class="goodList">
				<view class="list__item" v-for="(item,index) in goodsList" :key='item.goods_id' @tap="itemCellClick(item)"  >
					<view class="item__text">{{item.goods_name || ''}}</view>
					<view class="iconfont icon-youjiantou  arrow"></view>
				</view>
				<view class="loading" v-if="">{{ isFinished ? '没有更多数据了' : '加载中...' }}</view>
			</view>
		</view>
		<!-- 搜索历史记录 -->
		<view class="history__box" v-else :style="{ paddingTop: 60 + 'px'}">
			<view class="titleView">
				<view class="titleText">搜索历史</view>
				<view class="iconfont icon-shanchu" @tap="clearHistoryData"></view>
			</view>
			<view class="list">
				<view class="list__array" v-for="(item,index) in searchHistory" @tap="historyItemClick(item)" :key="index">
					<view class="list__item">{{item}}</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	export default {
		data() {
			return {
				timerId: null, // 定时器ID
				searchText: '', // 搜索文本
				goodsList: [], // 商品列表
				currentPage: 1, // 当前页码
				pageSize: 10, // 每页显示数量
				isFinished: false, // 是否加载完成
				searchHistory: [], // 搜索历史记录

			}
		},

		onLoad() {
			// 获取本地存储的搜索历史记录
			this.searchHistory = uni.getStorageSync('searchHistory') || []
		},

		// 监听用户下拉动作事件
		onPullDownRefresh() {
			this.currentPage = 1;
			this.getSearchResultList();
			console.log('--  滚到底部触发了,下拉刷新');
		},

		//  监听用户上拉触底事件
		onReachBottom() {
			// 滚动到底部时触发加载更多
			this.currentPage += 1;
			if (!this.isFinished) {
				this.getSearchResultList();
			}
			console.log('--  滚到底部触发了,上拉刷新');
		},


		methods: {
			
			// 单元格点击
			itemCellClick(item) {
				uni.navigateTo({
					url: '/pages/goods_detail/goods_detail' + '?goods_id=' + item.goods_id,
					success: res => {},
					fail: () => {},
					complete: () => {}
				});
			},
			
			//uniSearchBar 的 value 改变时触发事件，返回参数为uniSearchBar的value	
			inputChange(e) {
				console.log('--  显示输入的值:', e);
				//利用定时器触发搜索
				clearTimeout(this.timerId)
				this.timerId = setTimeout(() => {
					// this.searchText = e
					// 调用接口
					if (this.searchText.length > 0) {

						let searchHistory = uni.getStorageSync('searchHistory') || []

						// 检查搜索历史记录中是否已经存在当前搜索内容
						if (!searchHistory.includes(this.searchText)) {
							searchHistory.unshift(this.searchText)
							uni.setStorageSync('searchHistory', searchHistory)
						}

						//  触发下下拉刷新动画
						uni.startPullDownRefresh({
							complete() {
								this.getSearchResultList()
							}
						})
					}
				}, 1000);
			},

			// 获取搜索结果列表
			getSearchResultList() {

				let params = {
					query: this.searchText,
					page: this.currentPage,
					size: this.pageSize,
				};
				// 调用接口
				this.$reqGet('/api/public/v1/goods/search', params).then(res => {
					const code = res.statusCode;
					if (code == 200) {

						let total = res.data.message.total || 0
						
						if (this.currentPage <= 1) {
							this.goodsList = []
						}
						if (this.goodsList.length >= total) {
							this.isLoading = true
							uni.showToast({
								icon:'none',
								title: '没有更多数据了~'
							});
							return
						} else {
							this.currentPage++
							this.isLoading = false
							let list = res.data.message.goods || []
							this.goodsList = this.goodsList.concat(list)
						}
						// 停止刷新
						uni.stopPullDownRefresh();
					}
				})
			},

			// 搜索历史记录
			getSearchHistoryData() {
				let searchHistory = uni.getStorageSync('searchHistory') || []
				this.searchHistory = searchHistory
			},

			// 
			historyItemClick(item) {
				// 处理点击历史记录项的逻辑
				console.log('点击了历史记录项：', item);
				this.searchText = item
				this.inputChange(item)
			},

			// 搜索清除
			searchClear() {
				this.currentPage = 1
				this.goodsList = []
				this.searchText = ''
				this.getSearchHistoryData()
				console.log('--  清空了');
			},

			// 清除历史数据
			clearHistoryData() {

				uni.showModal({
					title: '',
					content: ' 确定要清除历史数据吗?',
					showCancel: true,
					cancelText: '取消',
					confirmText: '确定',
					success: res => {
						if (res.confirm) {
							// console.log('-- 点击了确认按钮');
							uni.removeStorageSync('searchHistory')
							this.searchHistory = []
						}
					},
					fail: () => {},
					complete: () => {}
				});
			}
		}
	}
</script>

<style scoped lang="scss">
	.search-box {
		position: fixed;
		left: 0;
		right: 0;
		background: #C00000;
	}

	.searchResult {
		.goodList {
			padding: 0 30rpx;

			.list__item {
				display: flex;
				align-items: center;
				justify-content: space-between;
				border-bottom: 2rpx solid #efefef;
				padding: 10rpx 0;

				.item__text {
					padding: 10rpx 0;
					font-size: 26rpx;
					color: #333;
					//  最多显示 3 行
					overflow: hidden;
					display: -webkit-box;
					-webkit-line-clamp: 3;
					-webkit-box-orient: vertical;
					text-overflow: ellipsis; // ... 替代
					white-space: normal; //nowrap 单行展示
					word-break: break-all;
				}

				.arrow {
					color: #999;
				}

				&:last-child {
					border-bottom: none;
				}
			}
		}

		.loading {
			padding: 20rpx 0;
			text-align: center;
			color: #999;
			font-size: 28rpx;
		}
	}

	.history__box {
		padding: 0 20rpx;
		// background-color: orange;

		.titleView {
			display: flex;
			align-items: center;
			justify-content: space-between;
			font-size: 28rpx;
			color: #333;
			padding: 20rpx 0;
			border-bottom: 1rpx solid #efefef;

			.titleText {}
		}

		.list {
			display: flex;
			align-items: center;
			font-size: 28rpx;
			color: #666;

			.list__array {
				margin-top: 20rpx;

				.list__item {
					padding: 10rpx 30rpx;
					border: 1rpx solid #efefef;
					border-radius: 100rpx;
					margin-right: 20rpx;
				}
			}
		}
	}
</style>